package com.example.comprehension.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

/**
 * Created by tong on 16/10/23.
 */
public class MyRelativeLayout extends RelativeLayout {
    GestureDetector mGD;
    private OnFlingListener mOnFlingListener;

    public MyRelativeLayout(Context context) {
        super(context);
    }

    public MyRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        mGD = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                int dx = (int) (e2.getX() - e1.getX()); //计算滑动的距离
                if (Math.abs(dx) > 30 && Math.abs(velocityX) > Math.abs(velocityY)) { //降噪处理，必须有较大的动作才识别
                    if (velocityX > 0) {
                        //向右边
                        //Toast.makeText(getContext(),"向右边",Toast.LENGTH_SHORT).show();
                        if (mOnFlingListener != null) {
                            mOnFlingListener.onFling(false);
                        }
                    } else {
                        //向左边
                        //Toast.makeText(getContext(),"向左边",Toast.LENGTH_SHORT).show();
                        if (mOnFlingListener != null) {
                            mOnFlingListener.onFling(true);
                        }
                    }
                    return true;
                } else {
                    return false; //当然可以处理velocityY处理向上和向下的动作
                }
            }
        });
    }

    public MyRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mGD.onTouchEvent(event);
        return true;
    }
    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return mGD.onTouchEvent(event);
    }

    public void setOnFlingListener(OnFlingListener listener) {
        this.mOnFlingListener = listener;
    }

    public interface OnFlingListener {
        void onFling(boolean left);
    }
}
